<template>
  <div class="strategy_canvas">
    <div class="operation_btn">
      <span> 策略流程配置</span>
      <el-button
        type="primary"
        class="btn-style"
        v-if="operationType == 'check'"
        @click="goBack"
        >返回</el-button
      >
      <el-button type="primary" class="btn-style" v-else @click="saveData"
        >保存</el-button
      >
    </div>

    <div class="policy_configuration">
      <el-row>
        <el-col :span="3" class="left-content">
          <el-collapse :value="['1', '2', '3', '4']">
            <el-collapse-item name="1">
              <template slot="title">
                内容策略
                <!-- <i class="header-icon el-icon-info"></i> -->
              </template>
              <div class="left_content_box">
                <div
                  class="left_content_item"
                  v-for="(item, index) in contentStrategyIconList"
                  :key="index"
                >
                  <img :src="item.iconImg" alt="" />
                  {{ item.text }}
                </div>
              </div>
            </el-collapse-item>
            <el-collapse-item title="客户分流" name="2">
              <div class="left_content_box">
                <div
                  class="left_content_item"
                  v-for="(item, index) in reachingStrategyyIconList"
                  :key="index"
                >
                  <img :src="item.iconImg" alt="" />
                  {{ item.text }}
                </div>
              </div>
            </el-collapse-item>
            <el-collapse-item title="控制策略" name="3">
              <div class="left_content_box">
                <div
                  class="left_content_item"
                  v-for="(item, index) in reachingStrategyyIconList1"
                  :key="index"
                >
                  <img :src="item.iconImg" alt="" />
                  {{ item.text }}
                </div>
              </div>
            </el-collapse-item>
            <el-collapse-item title="目标策略" name="4">
              <div class="left_content_box">
                <div
                  class="left_content_item"
                  v-for="(item, index) in targetStrategyIconList"
                  :key="index"
                >
                  <img :src="item.iconImg" alt="" />
                  {{ item.text }}
                </div>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-col>
        <el-col :span="21">
          <div class="workflow policy_canvas">
            <div
              class="approval-flow fd-nav-content"
              :style="{ top: `${needHeader ? '60px' : '0px'}` }"
            >
              <div class="dingflow-design">
                <div
                  class="box-scale"
                  id="box-scale"
                  :style="
                    'transform: scale(' +
                    nowVal / 100 +
                    '); transform-origin: 50% 0px 0px;'
                  "
                >
                  <nodeWrap
                    v-bind="$attrs"
                    v-model="nodeConfig"
                    :isTried="isTried"
                  ></nodeWrap>
                </div>
              </div>
            </div>
            <editor ref="editor"></editor>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import Editor from "./components/editor.vue";
import nodeWrap from "./components/nodeWrap.vue";
import { queryStrategyById, saveStrategyById } from "../../api/strategy/index";
export default {
  props: {
    needHeader: {
      type: Boolean,
      default: false,
    },
  },
  components: {
    nodeWrap,
    Editor,
  },
  data() {
    return {
      // 校验用
      isTried: true,
      // 报错的数据
      tipList: [],
      // 展示节点结构 初始化会更换为开始节点
      nodeConfig: {},
      // 缩放比例
      nowVal: 100,
      contentStrategyIconList: [
        {
          iconImg: require("./image/img1.png"),
          text: "文章",
        },
        {
          iconImg: require("./image/img2.png"),
          text: "线下活动",
        },
        {
          iconImg: require("./image/img3.png"),
          text: "线上活动",
        },
        {
          iconImg: require("./image/img4.png"),
          text: "H5海报",
        },
      ],
      reachingStrategyyIconList: [
        {
          iconImg: require("./image/img5.png"),
          text: "客户分流",
        },
      ],
      reachingStrategyyIconList1: [
        {
          iconImg: require("./image/img6.png"),
          text: "经营控制",
        },
      ],
      targetStrategyIconList: [
        {
          iconImg: require("./image/img7.png"),
          text: "目标设定",
        },
      ],
      baseDetailDrawer: false,
      flageTarge: false,
    };
  },
  // 让子组件都能拿到根节点 方便计算
  provide() {
    return {
      // 获取根节点的数据
      getRoot: () => this.nodeConfig,
      // 平铺所有节点
      getFlatRoot: () => this.getFlatDic(),
      findNode: this.findNode,
      openDrawer: this.openDrawer,
      // 用户options
      memberOptions: [
        {
          user_id: "asdbc",
          name: "测试数据",
        },
        {
          user_id: "asdbc2",
          name: "测试数据2",
        },
      ],
      // 选择类型
      typeOptions: {
        直属上级: 0,
        部门负责人: 1,
        指定成员: 2,
      },
      // 部门等级
      // levelOptions: this.$flowConfig.levelOptions,
      operatorList: this.$flowConfig.operatorList,
      dataFields: this.$flowConfig.dataFields,
      currentRuleData: {},
      operationType: "",
    };
  },
  created() {
    this.nodeConfig = {
      error: true,
      childNode: this.$factory.getStruct(null, this.$nodeType.开始, null, 1),
    };
    this.nodeConfig.childNode.childNode = this.$factory.getStruct(
      this.nodeConfig.childNode.nodeId,
      this.$nodeType.结束,
      null,
      1
    );
    localStorage.removeItem("baseDetailData");
    //获取地址栏参数
    this.strategyId = this.$route.query.id;
    this.operationType = this.$route.query.type;
    if (this.strategyId) {
      this.getStrategyCanvansList();
    }
  },
  methods: {
    async getStrategyCanvansList() {
      let params = { strategyId: this.strategyId || "" };
      queryStrategyById(params).then((response) => {
        if (response) {
          this.currentRuleData = response;
          this.currentRuleData = response;
          this.nodeConfig = JSON.parse(this.currentRuleData.flowConfigText);
          localStorage.setItem(
            "baseDetailData",
            JSON.stringify(this.nodeConfig.childNode.nodeDetail)
          );
        }
      });
    },
    saveData() {
      const baseDetailData = JSON.parse(localStorage.getItem("baseDetailData"));
      if (!baseDetailData) {
        this.$message({
          message: "请填写策略基础信息后保存",
          type: "warning",
        });
        this.visible = false;
        return;
      }

      if (
        this.nodeConfig &&
        this.nodeConfig.childNode.type == 0 &&
        this.nodeConfig.childNode.childNode.type === 10
      ) {
        this.$message({
          message: "请编辑策略流程后保存",
          type: "warning",
        });
        this.visible = false;
        return;
      }
      this.flageTarge = false;

      this.checkSaveData(this.nodeConfig);
      if (!this.flageTarge) {
        console.log(this.nodeConfig);
        // 调接口存数据
        let paramsData = {};
        paramsData.strategyId = this.strategyId || "";
        paramsData.strategyName = baseDetailData.strategyName || "";
        paramsData.strategyChannelCode =
          baseDetailData.strategyChannelCode || "";
        paramsData.strategyOrganId = baseDetailData.strategyOrganId || "";
        paramsData.strategyOrganName = baseDetailData.strategyOrganName || "";
        paramsData.customerGroup = baseDetailData.customerGroup || "";
        paramsData.strategyStatus = "ywc";
        paramsData.executeTime =
          baseDetailData.value1 && baseDetailData.policyType[0] == "1"
            ? baseDetailData.value1
            : "";
        paramsData.enterStartTime =
          baseDetailData.value1 && baseDetailData.policyType[0] == "1"
            ? baseDetailData.value2
            : "";
        paramsData.executeStartDateStr =
          baseDetailData.value3[0] && baseDetailData.policyType[0] == "2"
            ? baseDetailData.value3[0]
            : "";
        paramsData.executeEndDateStr =
          baseDetailData.value3[1] && baseDetailData.policyType[0] == "2"
            ? baseDetailData.value3[1]
            : "";
        paramsData.strategyExecuteType =
          baseDetailData.policyType[0] == "1"
            ? "one"
            : baseDetailData.policyType[0] == "2"
            ? "repeat"
            : "hand";
        paramsData.strategyDescribe = baseDetailData.strategyDesc || "";
        paramsData.flowConfigText = JSON.stringify(this.nodeConfig);
        paramsData.extraJson = JSON.stringify({
          frequency:
            baseDetailData.policyType[0] == "2" &&
            (baseDetailData.value8 == "1"
              ? "day"
              : baseDetailData.value8 == "2"
              ? "week"
              : baseDetailData.value8 == "3"
              ? ""
              : "month"),
          time:
            baseDetailData.value9 && baseDetailData.policyType[0] == "2"
              ? baseDetailData.value9
              : "",
          week:
            baseDetailData.week && baseDetailData.policyType[0] == "2"
              ? baseDetailData.week
              : "",
          month:
            baseDetailData.month && baseDetailData.policyType[0] == "3"
              ? baseDetailData.month
              : "",
        });
        this.saveRuleCanvas(paramsData);
      }
    },
    async saveRuleCanvas(paramsData) {
      let params = { ...paramsData };
      saveStrategyById(params).then((response) => {
        if (response) {
          this.$modal.msgSuccess(response.msg);
          this.$router.push("/policyIndex");
        }
      });
    },
    goBack() {
      this.$router.push("/policyIndex");
    },
    checkSaveData(data) {
      if (!data) {
        return;
      }
      if (!data.childNode && !data.conditionNodes && data.type != 1) {
        this.flageTarge = true;
        this.$message({
          message: "请确保所有分支末尾节点为目标节点",
          type: "warning",
        });
        return;
      }
      if (data.childNode && data.childNode.type == 10) {
        if (data.conditionNodes) {
          data.conditionNodes.forEach((item) => {
            this.checkSaveData(item);
          });
        } else {
          if (data.type != 1) {
            this.flageTarge = true;
            this.$message({
              message: "请确保所有分支末尾节点为目标节点",
              type: "warning",
            });
            return;
          } else {
            this.checkSaveData(data.conditionNodes);
          }
        }
      } else if (data.childNode) {
        this.checkSaveData(data.childNode);
      } else if (data.conditionNodes) {
        data.conditionNodes.forEach((item) => {
          this.checkSaveData(item);
        });
      }
    },
    saveBaseDetailDrawer() {},
    // 读取数据
    loadData(data) {
      // this.nodeConfig = data;
    },
    // 查找节点
    findNode(id) {
      let dic = this.getFlatDic();
      for (let kv in dic) {
        if (kv == id) {
          return dic[kv];
        }
      }
    },
    // 处理数组的问题 由于现在尾部缺失东西 导致会有点问题
    conditionNodesHandle(array, dic) {
      array.forEach((node) => {
        dic[node.nodeId] = node;
        node.childNode && this.flatData(node.childNode, dic);
      });
    },
    // 获取递归平铺字典
    getFlatDic() {
      let dic = {};
      this.flatData(this.nodeConfig, dic);
      return dic;
    },
    // 递归平铺所有节点 方便于节点的操作
    flatData(data, dic) {
      if (!data) return;
      if (data.nodeId) {
        dic[data.nodeId] = data;
      }
      if (data.childNode) {
        dic[data.childNode.nodeId] = data.childNode;
        this.flatData(data.childNode, dic);
        data.childNode.conditionNodes &&
          data.childNode.conditionNodes.length > 0 &&
          this.conditionNodesHandle(data.childNode.conditionNodes, dic);
      }
      if (data.conditionNodes && data.conditionNodes.length > 0) {
        this.conditionNodesHandle(data.conditionNodes, dic);
      }
    },
    // 保存前校验数据
    validate() {
      this.isTried = true;
      this.tipList = [];
      this.reErr(this.nodeConfig);
      return this.tipList.length == 0;
    },
    // 递归检验error
    reErr(data) {
      let nodeType = this.$nodeType;
      if (data.childNode) {
        this.reErr(data.childNode);
        if (data.childNode.type != nodeType.条件分支) {
          data.childNode.error &&
            this.tipList.push({
              name: data.childNode.nodeName,
              type: nodeType.toString(data.childNode.type),
            });
        } else {
          for (var i = 0; i < data.childNode.conditionNodes.length; i++) {
            if (data.childNode.conditionNodes[i].error) {
              this.tipList.push({
                name: data.childNode.conditionNodes[i].nodeName,
                type: "条件",
              });
            }
            this.reErr(data.childNode.conditionNodes[i]);
          }
        }
      }
    },
    // 缩放比例调整
    zoomSize(type) {
      let value = this.nowVal;
      if (!type && value > 50) {
        this.nowVal -= 10;
      } else if (type && value < 300) {
        this.nowVal += 10;
      }
    },
    // 打开编辑框
    openDrawer(priorityLevel, item, data, tip) {
      this.$refs.editor.openDrawer(priorityLevel, item, data, tip);
    },
  },
};
</script>

<style lang="less">
@import url("./styles/flow.less");
</style>
